import 'dart:convert';

import 'package:douhuaxiangsu/entity/canvas_step_type.dart';
import 'package:douhuaxiangsu/entity/canvas_type.dart';
import 'package:douhuaxiangsu/utils/image_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';

import '../entity/artwork_model.dart';
import '../widgets/point_style_dialog.dart';

/// 设置页组件
class CanvasSettingsPage extends StatefulWidget {
  final ArtworkModel artworkModel;

  const CanvasSettingsPage({super.key, required this.artworkModel});

  @override
  State<CanvasSettingsPage> createState() => _CanvasSettingsPageState();
}

class _CanvasSettingsPageState extends State<CanvasSettingsPage> {
  /// 作品数据
  ArtworkModel get artworkModel => widget.artworkModel;

  @override
  Widget build(BuildContext context) {
    var ctx = context;
    return Scaffold(
      appBar: AppBar(
        // 设置页标题
        title: const Text('设置'),
        leading: IconButton(
          // 返回按钮
          icon: const Icon(Icons.arrow_back),
          // 返回到上一页
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: ListView(
        children: [
          ListTile(
            title: const Text('画布大小'),
            subtitle: Text(
              '当前大小: ${artworkModel.canvas.size.x}x${artworkModel.canvas.size.y}',
            ),
            onTap: () {
              showDialog(
                context: context,
                builder: (BuildContext context) {
                  TextEditingController widthController = TextEditingController(
                    text: artworkModel.canvas.size.x.toString(),
                  );
                  TextEditingController heightController =
                      TextEditingController(
                        text: artworkModel.canvas.size.y.toString(),
                      );

                  return AlertDialog(
                    title: const Text('修改画布大小'),
                    content: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        if (CanvasType.square == artworkModel.canvas.type) ...[
                          Row(
                            children: [
                              Expanded(
                                child: TextField(
                                  controller: widthController,
                                  decoration: const InputDecoration(
                                    labelText: '宽度',
                                    border: OutlineInputBorder(),
                                  ),
                                  keyboardType: TextInputType.number,
                                ),
                              ),
                              const SizedBox(width: 8),
                              const Text('x'),
                              const SizedBox(width: 8),
                              Expanded(
                                child: TextField(
                                  controller: heightController,
                                  decoration: const InputDecoration(
                                    labelText: '高度',
                                    border: OutlineInputBorder(),
                                  ),
                                  keyboardType: TextInputType.number,
                                ),
                              ),
                            ],
                          ),
                        ] else
                          TextField(
                            controller: widthController,
                            decoration: const InputDecoration(
                              labelText: '尺寸',
                              border: OutlineInputBorder(),
                            ),
                            keyboardType: TextInputType.number,
                          ),
                      ],
                    ),
                    actions: [
                      TextButton(
                        onPressed: () => Navigator.of(context).pop(),
                        child: const Text('取消'),
                      ),
                      TextButton(
                        onPressed: () {
                          setState(() {
                            int
                            xPos =
                                int.tryParse(widthController.text) ??
                                artworkModel.canvas.size.x,
                            yPos = CanvasType.square == artworkModel.canvas.type
                                ? (int.tryParse(heightController.text) ??
                                      artworkModel.canvas.size.y)
                                : artworkModel.canvas.size.y;
                            var jsonUndo = jsonEncode({
                                  'x': artworkModel.canvas.size.x,
                                  'y': artworkModel.canvas.size.x,
                                }),
                                jsonExecute = jsonEncode({
                                  'x': xPos,
                                  'y': yPos,
                                });
                            artworkModel.canvas.stepIdx =
                                artworkModel.canvas.step.length;
                            artworkModel.canvas.step.add(
                              StepModel(
                                operate: CanvasStepType.resize,
                                jsonExecute: jsonExecute,
                                jsonUndo: jsonUndo,
                                execute: {},
                                undo: {},
                              ),
                            );
                            artworkModel.canvas.size.x = xPos;
                            artworkModel.canvas.size.y = yPos;
                          });
                          Navigator.of(context).pop();
                        },
                        child: const Text('确定'),
                      ),
                    ],
                  );
                },
              );
            },
          ),
          ListTile(
            title: Text(
              '${artworkModel.canvas.canvasConfig.showPosition ? '隐藏' : '显示'}坐标',
            ),
            subtitle: Text(
              '当前: ${artworkModel.canvas.canvasConfig.showPosition ? '显示' : '隐藏'}',
            ),
            onTap: () {
              setState(() {
                artworkModel.canvas.canvasConfig.showPosition =
                    !artworkModel.canvas.canvasConfig.showPosition;
              });
            },
          ),
          ListTile(
            title: Text(
              '${artworkModel.canvas.canvasConfig.showGrid ? '隐藏' : '显示'}网格',
            ),
            subtitle: Text(
              '当前: ${artworkModel.canvas.canvasConfig.showGrid ? '显示' : '隐藏'}',
            ),
            onTap: () {
              setState(() {
                artworkModel.canvas.canvasConfig.showGrid =
                    !artworkModel.canvas.canvasConfig.showGrid;
              });
            },
          ),
          ListTile(
            title: Text('修改像素点样式'),
            trailing: artworkModel.canvas.canvasConfig.pointStyle
                .getStyleWidget(),
            subtitle: Text(
              '当前: ${artworkModel.canvas.canvasConfig.pointStyle.getStyleText()}',
            ),
            onTap: () {
              showDialog(
                context: context,
                builder: (BuildContext context) {
                  return PointStyleDialog(
                    canvasConfig: artworkModel.canvas.canvasConfig,
                    onStyleChanged: () {
                      setState(() {});
                      if (artworkModel.canvas.canvasConfig.pointStyle.type ==
                          'custom') {
                        artworkModel.palette.data.map(
                          (colorItem) => {
                            ImageUtils.loadImageFromBase64WithColor(
                              artworkModel.canvas.canvasConfig.pointStyle.data,
                              Colors.grey,
                              width: 30,
                              height: 30,
                            ).then(
                              (tmpImg) => {
                                if (tmpImg != null)
                                  {
                                    artworkModel
                                            .canvas
                                            .canvasConfig
                                            .pointStyle
                                            .imageCacheMap[colorItem.color
                                            .toHexString()] =
                                        tmpImg,
                                  },
                              },
                            ),
                          },
                        );
                      }
                    },
                    ctx: ctx,
                  );
                },
              );
            },
          ),
        ],
      ),
    );
  }
}
